import axios from 'axios'
import { defineStore } from 'pinia'
import { useWebsocketStore } from '@/stores/websocket'

export const useUserStore = defineStore('user', {
    state: () => ({
        id: '',
        username: '',
        photo: '',
        level: '',
        rating: '',
        token: '',
        is_login: false,
        loading: false,
        error: null,
    }),
    actions: {
        updateUser(user) {
            this.id = user.id
            this.username = user.username
            this.photo = user.photo
            this.level = user.level
            this.rating = user.rating
            this.is_login = user.is_login
        },
        updateToken(token) {
            this.token = token
        },
        async login(account, password) {
            this.loading = true
            this.error = null

            try {
                const response = await axios.post('http://127.0.0.1:8080/api/user/account/login/', {
                    account: account.trim(),
                    password,
                })

                const result = response.data
                if (result.code === 1) {
                    // 登录成功，保存token和用户信息
                    const { token, user } = result.data

                    // 存储token并更新状态
                    localStorage.setItem('token', token)
                    this.updateToken(token)
                    this.updateUser({
                        ...user,
                        is_login: true,
                    })

                    // 登录成功后，获取websocket连接
                    const websocketStore = useWebsocketStore()
                    websocketStore.connectAfterLogin(this.token)

                    return true
                } else {
                    // 登录失败
                    this.error = result.msg || '账号或密码错误'
                    return false
                }
            } catch (error) {
                console.error('登录请求错误:', error)
                if (error.response?.data?.msg) {
                    this.error = error.response.data.msg
                } else {
                    this.error = '服务器连接异常，请稍后重试'
                }
                return false
            } finally {
                this.loading = false
            }
        },
        async registerUser(userData) {
            this.loading = true
            this.error = null

            try {
                const response = await axios.post(
                    'http://127.0.0.1:8080/api/user/account/register/',
                    userData
                )

                const result = response.data
                if (result.code === 1) {
                    // 注册成功
                    return true
                } else {
                    // 注册失败
                    this.error = result.msg || '注册失败，请稍后重试'
                    return false
                }
            } catch (error) {
                console.error('注册请求错误:', error)
                if (error.response?.data?.msg) {
                    this.error = error.response.data.msg
                } else {
                    this.error = '服务器连接异常，请稍后重试'
                }
                return false
            } finally {
                this.loading = false
            }
        },
        logout() {
            // 先断开WebSocket连接
            const websocketStore = useWebsocketStore()
            websocketStore.disconnect()

            // 清除用户信息和token
            this.updateUser({
                id: '',
                username: '',
                photo: '',
                level: '',
                rating: '',
                is_login: false,
            })
            this.updateToken('')
            localStorage.removeItem('token') // 从本地存储中移除token
        },
        async getinfo(data) {
            axios
                .get('http://127.0.0.1:8080/api/user/account/info/', {
                    headers: {
                        Authorization: 'Bearer ' + this.token,
                    },
                })
                .then((response) => {
                    const result = response.data
                    if (result.code === 1) {
                        this.updateUser({
                            ...result.data,
                            is_login: true,
                        })
                        // 获取用户信息成功后，检查并建立WebSocket连接
                        const websocketStore = useWebsocketStore()
                        if (!websocketStore.connected) {
                            websocketStore.initConnection()
                        }
                        data.success()
                    }
                })
                .catch((resp) => {
                    data.error(resp.data)
                    console.log(resp.data)
                })
        },
    },
})
